package com.hcc.gateway.app;

import com.hcc.gateway.app.config.HccGatewayConfig;
import com.hcc.gateway.netty.config.GatewayConfig;
import com.hcc.gateway.netty.server.GatewayServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;

import javax.annotation.PreDestroy;

/**
 * HccGatewayApplication
 *
 * @author hushengjun
 * @date 2021/12/25
 */
@Slf4j
@SpringBootApplication(scanBasePackages = "com.hcc.gateway")
public class HccGatewayApplication implements ApplicationListener<ApplicationStartedEvent> {

    private GatewayServer server;

    @Autowired
    private HccGatewayConfig hccGatewayConfig;

    public static void main(String[] args) {
        new SpringApplicationBuilder(HccGatewayApplication.class)
                .bannerMode(Banner.Mode.OFF)
                .web(WebApplicationType.NONE)
                .run(args);
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        GatewayConfig config = new GatewayConfig();
        BeanUtils.copyProperties(hccGatewayConfig, config);
        // 启动网关
        this.server = new GatewayServer(config);
        server.start();
    }

    @PreDestroy
    public void destroy() {
        // 关闭网关
        server.shutdown();
        log.info("hcc-gateway已关闭！");
    }

}
